﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Newtonsoft.Json;
using QDT.Common;
using QDT.Core.Deals;
using QDT.Core.Members;
using QDT.Core.Projects;
using QDT.Web.Models;

namespace QDT.Web.Controllers
{
    public partial class AppController
    {

        public JsonResult AppLogin(string router)
        {
            var model = JsonConvert.DeserializeObject<AppLoginModel>(string.IsNullOrEmpty(router) ? "" : router);
            var member = DbProvider.D<User>().FirstOrDefault(x => x.UserName == model.username || x.Email == model.username || x.Mobile == model.username);
            if (member == null || member.IsBorrower)
            {
                return Json(new {result = "0"}, JsonRequestBehavior.AllowGet);
            }
            if(member.Password != model.password.ToUpper() )
            {
                return Json(new { result = "-1" }, JsonRequestBehavior.AllowGet);
            }
            var user = new UserDto(member);
            return Json(new { result = "1", user }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AppRegister(string router)
        {
            var model = JsonConvert.DeserializeObject<AppRegisterModel>(string.IsNullOrEmpty(router) ? "" : router);

            if (model.password != model.confirmpassword)
            {
                return Json(new { result = "-1", msg = "两次密码不匹配" }, JsonRequestBehavior.AllowGet);
            }

            if (!(model.username + model.mobile + model.password + SecretKey).Hash().ToUpper().Equals(model.token.ToUpper()))
            {
                return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);
            }

            if (DbProvider.D<User>().Count(x => x.UserName == model.username) > 0) return Json(new { result = "-2", msg = "用户名已被注册" }, JsonRequestBehavior.AllowGet);
            if (DbProvider.D<User>().Any(x => x.Mobile == model.mobile && x.MobilePassed)) return Json(new { result = "-3", msg = "手机号已被注册" }, JsonRequestBehavior.AllowGet);
            if (string.IsNullOrWhiteSpace(model.password)) return Json(new { result = "0" }, JsonRequestBehavior.AllowGet);
            var user = new User
            {
                GroupID = 3,
                IsLender = true,
                IsBorrower = false,
                IsEffect = true,
                UserName = model.username,
                Password = model.password.ToUpper(),
                UserAccount = new UserAccount()
            };
            user.BindMobile(model.mobile);
            DbProvider.Add(user);
            DbProvider.SaveChanges();

            return Json(new { result = "1", id = user.ID.ToString(), msg = "注册成功" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult BindEmail(string router)
        {
            var model = JsonConvert.DeserializeObject<BindEmailModel>(string.IsNullOrEmpty(router) ? "" : router);
            if (!(model.id + model.email + SecretKey).Hash().ToUpper().Equals(model.token.ToUpper()))
            {
                return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);
            }

            if (DbProvider.D<User>().Any(x => x.Email == model.email && x.EmailPassed)) return Json(new { result = "-3", msg = "邮箱已被注册" }, JsonRequestBehavior.AllowGet);

            var user = DbProvider.GetByID<User>(model.id);

            if (user == null) return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);

            user.BindEmail(model.email);
            DbProvider.SaveChanges();

            return Json(new { result = "1", msg = "绑定成功" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult BindIdCard(string router)
        {
            var model = JsonConvert.DeserializeObject<BindIdCardModel>(string.IsNullOrEmpty(router) ? "" : router);
            if (!(model.id + model.idcard + model.realname + SecretKey).Hash().ToUpper().Equals(model.token.ToUpper()))
            {
                return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);
            }

            bool idHasPass = DbProvider.D<User>().Any(x => x.IDCardPassed && x.IDCard.Equals(model.idcard) && x.GroupID == 3);
            if (idHasPass)
            {
                return Json(new { result = "-3", msg = "此身份证已验证，不能重复验证！" }, JsonRequestBehavior.AllowGet);
            }

            var user = DbProvider.GetByID<User>(model.id);

            if (user == null) return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);

            if (user.IDCardPassed)
            {
                return Json(new { result = "-1", msg = "身份证已验证，不能修改！" }, JsonRequestBehavior.AllowGet);
            }

            if (user.IdValidatorTime >= 3)
            {
                return Json(new { result = "-2", msg = "身份证验证次数超过规定次数，请联系客服进行身份证验证！" }, JsonRequestBehavior.AllowGet);
            }

            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            var validator = new QueryValidatorService();

            string userinfo = "{0},{1}".FormatWith(model.realname, model.idcard.ToUpper());
            string result = validator.querySingle("qiandaitong".ToDesEncrypt(), "qiandaitong_B97v_b6^".ToDesEncrypt(),
                                                  "1A020201".ToDesEncrypt(),
                                                  userinfo.ToDesEncrypt());
            if (!string.IsNullOrWhiteSpace(result))
            {
                string re = result.ToDesDecrypt();
                var xd = new XmlDocument();
                xd.LoadXml(re);
                XmlNode xmlRoot = xd.SelectSingleNode("data");
                if (xmlRoot != null)
                {
                    XmlNode messageNode = xmlRoot.ChildNodes[0];
                    string messageStatus = messageNode.ChildNodes[0].InnerText;
                    XmlNode checkInfosNode = xmlRoot.ChildNodes[1];
                    XmlNode checkInfoNode = checkInfosNode.ChildNodes[0];
                    string compStatus = checkInfoNode.ChildNodes[3].InnerText;

                    if (messageStatus == "0")
                    {
                        user.IdValidatorTime++;
                        if (compStatus == "3")
                        {
                            user.BindIDCard(model.idcard, model.realname);
                            DbProvider.SaveChanges();
                            return Json(new { result = "1", msg = "身份认证成功" }, JsonRequestBehavior.AllowGet);
                        }
                        DbProvider.SaveChanges();
                        return Json(new { result = "-4", msg = "身份认证失败，请正确填写您的真实姓名和身份证号！" }, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult QueryAccount(string router)
        {
            var model = JsonConvert.DeserializeObject<UserQueryModel>(string.IsNullOrEmpty(router) ? "" : router);

            if (!(model.id + SecretKey).Hash().Equals(model.token.ToUpper()))
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }

            var user = DbProvider.GetByID<User>(model.id);
            var account = new UserAccountDto(user)
            {
                investcount = DbProvider.D<Credit>().Count(x => x.UserID == user.ID).ToString("0")
            };
            return Json(new { account = account }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ChangePassword(string router)
        {
            var model = JsonConvert.DeserializeObject<ChangePasswordModel>(string.IsNullOrEmpty(router) ? "" : router);
            if (!(model.mobile + model.newpassword + SecretKey).Hash().ToUpper().Equals(model.token.ToUpper()))
            {
                return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);
            }
            var user = DbProvider.D<User>().FirstOrDefault(x => x.Mobile == model.mobile && x.MobilePassed);
            if (user == null) return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);

            user.Password = model.newpassword.ToUpper();
            DbProvider.SaveChanges();

            return Json(new { result = "1", msg = "修改成功" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult InvestList(string router)
        {

            var model = JsonConvert.DeserializeObject<UserQueryModel>(string.IsNullOrEmpty(router) ? "" : router);

            if (!(model.id + SecretKey).Hash().Equals(model.token.ToUpper()))
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }

            var credits = DbProvider.D<Credit>().Where(x => x.UserID == model.id).OrderBy(x => x.InnerStatus).ThenByDescending(x => x.ID)
                    .ToPagedList(0, 50).ToList();
            ICollection<InvestRecordDto> invests = new Collection<InvestRecordDto>();
            credits.Each(x => invests.Add(new InvestRecordDto(x)
            {
                projectname = DbProvider.D<Project>().FirstOrDefault(p => p.ID == x.ProjectID).Name
            }));

            return Json(new { invests }, JsonRequestBehavior.AllowGet);

        }

        public JsonResult LogList(string router)
        {
            var model = JsonConvert.DeserializeObject<UserQueryModel>(string.IsNullOrEmpty(router) ? "" : router);

            if (!(model.id + SecretKey).Hash().Equals(model.token.ToUpper()))
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }

            var logs = DbProvider.D<UserTransLog>().Where(x => x.UserID == model.id).OrderByDescending(x => x.ID)
                    .ToPagedList(0, 50).ToList();
            ICollection<UserLogDto> invests = new Collection<UserLogDto>();
            logs.Each(x => invests.Add(new UserLogDto(x)));

            return Json(new { invests }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult BindMobile(string router)
        {
            var model = JsonConvert.DeserializeObject<BindMobileModel>(string.IsNullOrEmpty(router) ? "" : router);
            if (!(model.id + model.mobile + SecretKey).Hash().ToUpper().Equals(model.token.ToUpper()))
            {
                return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);
            }

            if (DbProvider.D<User>().Any(x => x.Mobile == model.mobile && x.EmailPassed)) return Json(new { result = "-3", msg = "邮箱已被注册" }, JsonRequestBehavior.AllowGet);

            var user = DbProvider.GetByID<User>(model.id);

            if (user == null) return Json(new { result = "-999", msg = "未知异常" }, JsonRequestBehavior.AllowGet);

            user.BindMobile(model.mobile);
            DbProvider.SaveChanges();

            return Json(new { result = "1", msg = "绑定成功" }, JsonRequestBehavior.AllowGet);
        }

    }
}
